package com.example.servlet;

import com.example.model.Article;
import com.example.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet(name = "ArticleDetailServlet", urlPatterns = "/article-detail")
public class ArticleDetailServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String idStr = req.getParameter("id");
        int id = -1;
        try {
            if (idStr == null || idStr.trim().isEmpty()) {
                // id为空，跳转到文章列表页或首页
                resp.sendRedirect("article.jsp");
                return;
            }
            id = Integer.parseInt(idStr);
        } catch (NumberFormatException e) {
            // id不是数字，跳转到文章列表页或首页
            resp.sendRedirect("article.jsp");
            return;
        }
        Article article = null;
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement("SELECT * FROM articles WHERE id=?")) {
            ps.setInt(1, id);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    article = new Article();
                    article.setId(rs.getInt("id"));
                    article.setTitle(rs.getString("title"));
                    article.setType(rs.getString("type"));
                    article.setContent(rs.getString("content"));
                    article.setAuthor(rs.getString("author"));
                    article.setCreateTime(rs.getTimestamp("create_time"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 增加浏览量
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement ps = conn.prepareStatement("UPDATE articles SET views = views + 1 WHERE id = ?")) {
            ps.setInt(1, id);
            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        req.setAttribute("article", article);
        req.getRequestDispatcher("article-detail.jsp").forward(req, resp);
    }
} 